package day_2022_7_to_8.day48;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author haomin
 * @date 2022/08/31 20:54
 **/
public class Day46_11_Offer32_Ⅱ_LevelOrder {
    class Solution {
        public List<List<Integer>> levelOrder(TreeNode root) {
            if(root == null) return new ArrayList<>();
            List<List<Integer>> res = new ArrayList<>();
            Queue<TreeNode> queue = new LinkedList<>();
            queue.offer(root);
            while(!queue.isEmpty()){
                List<Integer> ret = new ArrayList<>();
                int size = queue.size();
                for(int i = 0; i < size; ++i){
                    TreeNode cur = queue.poll();
                    ret.add(cur.val);
                    if(cur.left != null) queue.offer(cur.left);
                    if(cur.right != null) queue.offer(cur.right);
                }
                res.add(ret);
            }
            return res;
        }
    }
    class Solution2 {
        List<List<Integer>> res = new ArrayList<>();
        public List<List<Integer>> levelOrder(TreeNode root) {
            preOrder(root, 0);
            return res;
        }
        private void preOrder(TreeNode root, int k){
            if(root == null) return;
            if(res.size() <= k) res.add(new ArrayList());
            res.get(k).add(root.val);
            preOrder(root.left, k + 1);
            preOrder(root.right, k + 1);
        }
    }
}